package com.cdivtc.management.service;


import com.cdivtc.management.pojo.Result;
import com.cdivtc.management.shiro.JwtToken;
import com.cdivtc.management.utils.JsonUtils;
import com.cdivtc.management.utils.JwtUtil;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.subject.Subject;
import org.apache.shiro.web.filter.authc.BasicHttpAuthenticationFilter;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.annotation.RequestMethod;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Date;

@Component
public class JwtFilter extends BasicHttpAuthenticationFilter {
    private static final Logger logger = LoggerFactory.getLogger(JwtFilter.class);

    /**
     * 执行登录认证
     *
     * @param request
     * @param response
     * @param
     * @return
     */
    @Override
    protected boolean isAccessAllowed(ServletRequest request, ServletResponse response, Object mappedValue) {
        Date date = new Date();
        Cookie[] cookies = ((HttpServletRequest) request).getCookies();

        response.setCharacterEncoding("utf-8");
        Result result1 = new Result();
        response.setContentType("text/html;charset=UTF-8");
//判断是否需要进行权限拦截
        String[] rolesArray = (String[]) ((String[]) mappedValue);
        String authorization = ((HttpServletRequest) request).getHeader("Authorization");
        if (rolesArray == null || rolesArray.length == 0) {
//                不拦截任何角色
            return true;
        } else {
            //判断请求的请求头是否带上 "Token"
            if (authorization != null && authorization.length() > 0) {
                //如果存在，则进入 executeLogin 方法执行登入，检查 token 是否正确
                if (JwtUtil.verify(authorization)) {
                    Subject subject = this.getSubject(request, response);
                    if (rolesArray != null && rolesArray.length != 0) {
                        JwtToken token = new JwtToken(authorization);
                        this.getSubject(request, response).login(token);
                        for (int i = 0; i < rolesArray.length; i++) {

                            if (subject.hasRole(rolesArray[i])) {
                                // 若当前用户是rolesArray中的任何一个，则有权限访问
                                return true; }
                        }
                    } else { return true; }
                }

            }

            response.setContentType("application/json; charset=utf-8");
            //如果请求头不存在 Token，则可能是执行登陆操作或者是游客状态访问，无需检查 token，直接返回 true
            result1.error("权限认证失败");
            String s = JsonUtils.objectToJson(result1);
            try {
                response.getWriter().println(s);
            } catch (IOException e) {
                e.printStackTrace();
            }

        }
        return false;
    }

    /**
     * 对跨域提供支持
     */
    @Override
    protected boolean preHandle(ServletRequest request, ServletResponse response) throws Exception {
        HttpServletRequest httpServletRequest = (HttpServletRequest) request;
        HttpServletResponse httpServletResponse = (HttpServletResponse) response;
        httpServletResponse.setHeader("Access-control-Allow-Origin", httpServletRequest.getHeader("Origin"));
        httpServletResponse.setHeader("Access-Control-Allow-Methods", "GET,POST,OPTIONS,PUT,DELETE");
        httpServletResponse.setHeader("Access-Control-Allow-Headers", httpServletRequest.getHeader("Access-Control-Request-Headers"));
        httpServletResponse.setHeader("Access-Control-Expose-Headers","Authorization");
        // 跨域时会首先发送一个option请求，这里我们给option请求直接返回正常状态
        if (httpServletRequest.getMethod().equals(RequestMethod.OPTIONS.name())) {
            httpServletResponse.setStatus(HttpStatus.OK.value());
            return false;
        }

        return super.preHandle(request, response);
    }

    @Override
    protected AuthenticationToken createToken(ServletRequest servletRequest, ServletResponse servletResponse) {

        HttpServletRequest request = (HttpServletRequest) servletRequest;
        String token = request.getHeader("Authorization");

        return new JwtToken(token);
    }

}